<template>
  <div class="production-query">
    <div class="stars"></div>
    <div class="shooting-stars"></div>
    
    <div class="content-layout">
      <div class="side-space"></div>
      <div class="chat-container">
        <div class="chat-module">
          <!-- 标题部分 -->
          <div class="chat-title">
            <h2>MES 智能对话系统</h2>
          </div>
          
          <!-- 消息对话部分 -->
          <div class="chat-messages">
            <template v-for="(message, index) in messages" :key="index">
              <div v-if="shouldShowTime(message, index)" class="message-time">
                {{ formatMessageTime(message.timestamp) }}
              </div>
              <div 
                class="message-item"
                :class="message.type"
              >
                <template v-if="message.type === 'response' && message.data">
                  {{ message.content }}
                  <template v-if="message.data.total > 0">
                    <div 
                      class="clickable-count"
                      @click="showDataTable(message.data)"
                    >
                      查看需要处理数量为{{ message.data.total }}
                    </div>
                    <div 
                      class="process-link" 
                      :class="{ 'disabled': message.processed }"
                      @click="!message.processed && handleProcess(message)"
                    >
                      点击处理
                    </div>
                  </template>
                </template>
                <template v-else>
                  {{ message.content }}
                </template>
              </div>
            </template>
          </div>
          
          <!-- 按钮操作区 -->
          <div class="chat-actions">
            <el-button 
              type="primary" 
              @click="showQueryConditions"
            >执行查询条件</el-button>
            
            <!-- 添加条件输入区域 -->
            <div v-if="selectedCondition" class="query-input-group">
              <span class="condition-label">{{ selectedCondition }}</span>
              <el-input
                v-model="queryInput"
                :placeholder="getPlaceholder"
                class="query-input"
                clearable
                :disabled="false"
              ></el-input>
            </div>
            
            <el-button 
              type="success" 
              @click="handleQuery" 
              :disabled="isQuerying"
            >查询</el-button>
          </div>
        </div>
      </div>
      <div class="side-space"></div>
    </div>

    <!-- 查询条件弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="选择查询条件"
      width="30%"
      center
    >
      <div class="dialog-content">
        <el-radio-group v-model="queryType">
          <div class="radio-item">
            <el-radio :label="1">智电工单颜色异常处理</el-radio>
          </div>
          <div class="radio-item">
            <el-radio :label="2">串焊机追溯</el-radio>
          </div>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmQueryCondition">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加数据表格弹窗 -->
    <el-dialog
      v-model="tableVisible"
      title="异常数据详情"
      width="80%"
      center
      class="data-dialog"
    >
      <div class="table-wrapper">
        <div class="table-container">
          <el-table 
            :data="paginatedTableData" 
            style="width: 100%" 
            border
            :cell-style="cellStyle"
            :header-cell-style="headerCellStyle"
          >
            <el-table-column
              v-for="(col, index) in tableColumns"
              :key="index"
              :prop="col.prop"
              :label="col.label"
              :width="col.width"
              align="center"
              header-align="center"
              show-overflow-tooltip
            />
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="tableData.length"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tableVisible = false">关闭</el-button>
          <el-button type="primary" @click="downloadData">
            下载数据
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const queryType = ref<number | null>(null)  // 修改为 null，表示默认不选择
const isQuerying = ref(false)
const queryInput = ref('')
const selectedCondition = ref('')

// 获取输入框提示文本
const getPlaceholder = computed(() => {
  return queryType.value === 1 ? '请输入工单号' : ''
})

// 显示查询条件弹窗
const showQueryConditions = () => {
  dialogVisible.value = true
}

// 确认查询条件
const confirmQueryCondition = () => {
  if (!queryType.value) {
    // 如果未选择条件，不关闭弹窗
    return
  }
  
  // 设置选中的条件文本
  selectedCondition.value = queryType.value === 1 
    ? '智电工单颜色异常处理' 
    : queryType.value === 2 
      ? '串焊机追溯' 
      : ''
  
  // 清空输入框
  queryInput.value = ''
  dialogVisible.value = false
}

// 修改消息类型定义
interface Message {
  content: string;
  type: string;
  timestamp: number;
  data?: any;
  processed?: boolean;  // 添加处理状态标记
}

// 修改消息列表
const messages = ref<Message[]>([])

// 添加时间处理函数
const formatMessageTime = (timestamp: number) => {
  const date = new Date(timestamp);
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    hour12: false 
  });
};

// 判断是否需要显示时间
const shouldShowTime = (message: Message, index: number) => {
  if (index === 0) return true;
  const prevMessage = messages.value[index - 1];
  const timeDiff = message.timestamp - prevMessage.timestamp;
  return timeDiff > 5 * 60 * 1000; // 超过5分钟显示时间
};

// 添加表格相关的响应式变量
const tableVisible = ref(false)
const tableData = ref([])
const tableColumns = ref([
  { prop: 'WO_ID', label: '工单号', width: '180' },  // 添加工单号列
  { prop: 'LOT_ID', label: '批次号', width: '180' },
  { prop: 'COLOUR', label: '颜色', width: '120' },
  { prop: 'EFF', label: '效率', width: '120' },
  { prop: 'CREATED', label: '创建时间', width: '220' },
  { prop: 'PARENT_LOT_RRN', label: '箱号', width: '180' }
])

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(10)

// 计算分页后的表格数据
const paginatedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 处理每页条数改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1  // 重置第一页
}

// 添加检查电池ID重复和FX的函数
const checkBatteryData = (data: any[]) => {
  // 统计电池ID重复
  const batteryIds = data.map(item => item.BatterylD);
  const duplicates = batteryIds.filter((item, index) => batteryIds.indexOf(item) !== index);
  const duplicateRate = (duplicates.length / batteryIds.length) * 100;

  // 检查FX标记
  const hasFX = data.some(item => item.BatterylD?.includes('FX'));
  
  // 获取排版机ID
  const equipmentId = data[0]?.EquipmentID || '未知';

  return {
    duplicateRate,
    hasFX,
    equipmentId
  };
};

// 修改处理查询操作
const handleQuery = async () => {
  if (!queryInput.value && selectedCondition.value) {
    return;
  }
  
  isQuerying.value = true;
  
  try {
    if (queryType.value === 2) { // 串焊机追溯
      messages.value.push({
        content: `正在查询组件：${queryInput.value}`,
        type: 'query',
        timestamp: Date.now()
      });

      // 先查询玻璃数据
      const glassResponse = await axios.get(`/api/db/selectGlass/${queryInput.value}`);
      const glassData = glassResponse.data.data;

      if (glassData.total > 0) {
        // 如果找到玻璃数据
        messages.value.push({
          content: '正在查询组件玻璃ID绑定数据',
          type: 'response',
          timestamp: Date.now()
        });

        // 修改这里：确保正确获取 GLASS_ID
        const glassRecord = glassData.list[0];
        if (!glassRecord || !glassRecord.GLASS_ID) {
          throw new Error('未找到有效的玻璃ID');
        }

        // 查询电池绑定数据
        const batteryResponse = await axios.get(`/api/db/selectBattery/${glassRecord.GLASS_ID}`);
        const batteryData = batteryResponse.data.data;

        if (batteryData.total === 0) {
          messages.value.push({
            content: 'MES没有排版机绑定数据',
            type: 'response',
            timestamp: Date.now()
          });
        } else if (batteryData.total === 12) {
          // 检查电池数据
          const { duplicateRate, hasFX, equipmentId } = checkBatteryData(batteryData.list);

          if (duplicateRate > 50) {
            messages.value.push({
              content: `该排版机(${equipmentId})绑定的串ID异常，串ID重复，需要串焊机厂商查看`,
              type: 'response',
              timestamp: Date.now()
            });
          } else if (hasFX) {
            messages.value.push({
              content: `该组件绑定的排版机(${equipmentId})为返修机台返修组件`,
              type: 'response',
              timestamp: Date.now()
            });
          } else {
            messages.value.push({
              content: '绑定正常，无重复无返修',
              type: 'response',
              timestamp: Date.now()
            });
          }
        } else if (batteryData.total > 12) {
          messages.value.push({
            content: '绑定排版机异常，玻璃ID重复需要晟成查看',
            type: 'response',
            timestamp: Date.now()
          });
        }
      } else {
        // 如果没找到玻璃数据，查询组件数据
        const lotResponse = await axios.get(`/api/db/selectLot/${queryInput.value}`);
        const lotData = lotResponse.data.data;

        if (!lotData.list || lotData.list.length === 0) {
          messages.value.push({
            content: '组件在mes中不存在',
            type: 'response',
            timestamp: Date.now()
          });
        } else {
          messages.value.push({
            content: '当前组件未过站或跳站',
            type: 'response',
            timestamp: Date.now()
          });
        }
      }
    } else if (queryType.value === 1) {
      // 原有的智电工单颜色异常处理逻辑保持不变
      const response = await axios.get(`/api/db/selectColor/${queryInput.value}`);
      const responseData = response.data.data;
      
      let messageContent = '';
      if (!responseData.list || responseData.list.length === 0) {
        messageContent = '智电工单颜色正常不需要处理';
      } else {
        messageContent = '智电工单颜色异常，';
      }
      
      messages.value.push({
        content: messageContent,
        type: 'response',
        timestamp: Date.now(),
        data: responseData
      });
    }
  } catch (error: any) {
    messages.value.push({
      content: `查询失败：${error.message}`,
      type: 'error',
      timestamp: Date.now()
    });
  } finally {
    isQuerying.value = false;
  }
};

// 显示数据表格
const showDataTable = (data: any) => {
  tableData.value = data.list || []
  currentPage.value = 1  // 重置页码
  tableVisible.value = true
}

// 下载数据
const downloadData = () => {
  const data = tableData.value;
  const headers = tableColumns.value.map(col => col.label).join(',');
  const rows = data.map((row: any) => 
    tableColumns.value.map(col => row[col.prop]).join(',')
  ).join('\n');
  
  const csvContent = `${headers}\n${rows}`;
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  
  link.setAttribute('href', url);
  link.setAttribute('download', `异常数据_${new Date().toLocaleDateString()}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 修改处理函数
const handleProcess = async (message: any) => {
  if (message.processed) return;
  
  try {
    // 使用工单号进行更新
    const woId = message.data.list[0].WO_ID;
    const response = await axios.post(`/api/db/updateColor/${woId}`);
    
    if (response.data.success) {
      message.processed = true;
      ElMessage.success('处理成功');
      
      // 添加处理成功的对话消息
      messages.value.push({
        content: `工单 ${woId} 的颜色已更新为DA`,
        type: 'response',
        timestamp: Date.now()
      });
      
      // 关闭表格弹窗
      tableVisible.value = false;
    }
  } catch (error: any) {
    ElMessage.error(`处理失败: ${error.message}`);
    
    // 添加处理失败的对话消息
    messages.value.push({
      content: `工单 ${message.data.list[0].WO_ID} 颜色更新失败：${error.message}`,
      type: 'error',
      timestamp: Date.now()
    });
  }
}

// 修改表格样式方法
const cellStyle = {
  textAlign: 'center',
  padding: '8px 0',
  height: '40px',
  lineHeight: '40px',  // 修改行高以垂直居中
  color: '#606266'  // 添加文字颜色
}

const headerCellStyle = {
  textAlign: 'center',
  background: '#f5f7fa',
  height: '40px',
  lineHeight: '40px',  // 修改行高以垂直居中
  padding: '8px 0',
  fontWeight: 'bold',
  color: '#303133'  // 添加表头文字颜色
}
</script>

<style scoped>
:deep(body),
:deep(html) {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
}

.production-query {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  background: radial-gradient(ellipse at bottom, #1B2735 0%, #090A0F 100%);
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.content-layout {
  display: flex;
  height: 100%;
  position: relative;
  z-index: 1;
}

.side-space {
  flex: 1;
}

.chat-container {
  flex: 2;
  padding: 20px;
}

.chat-module {
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  height: 100%;
  padding: 20px;
  color: white;
}

.chat-title {
  text-align: center;
  margin-bottom: 20px;
}

.chat-title h2 {
  color: #fff;
  font-size: 24px;
  margin: 0;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  margin: 20px 0;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  display: flex;
  flex-direction: column;
}

.chat-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
}

.query-input-group {
  display: flex;
  align-items: center;
  gap: 15px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 15px;
  border-radius: 20px;
  backdrop-filter: blur(5px);
}

.condition-label {
  color: #fff;
  white-space: nowrap;
  font-size: 14px;
}

.query-input {
  width: 240px;
}

:deep(.el-input__wrapper) {
  background: transparent;
  box-shadow: none !important;
  padding: 0;
}

:deep(.el-input__inner) {
  color: #fff !important;
  background: transparent !important;
  border: none;
  height: 32px;
  line-height: 32px;
  padding: 0;
  font-size: 14px;
}

:deep(.el-input__wrapper:hover),
:deep(.el-input__wrapper.is-focus) {
  background: transparent;
  box-shadow: none !important;
}

:deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

.radio-item {
  margin: 10px 0;
}

:deep(.el-input__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff !important;
  cursor: text !important;
}

:deep(.el-input__inner:focus) {
  background: rgba(255, 255, 255, 0.15);
}

:deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5);
}

/* 修改弹窗的单框间距 */
.dialog-content .el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 自定义弹窗样式 */
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 15px;
}

.dialog-content {
  padding: 20px 0;
}

:deep(.el-radio) {
  color: #333;
}

/* 修改消息样式，模仿微信 */
.message-item {
  margin: 10px 0;
  padding: 12px 16px;
  border-radius: 4px 18px 18px 18px;
  max-width: 70%;
  word-break: break-word;
  position: relative;
  font-size: 14px;
  line-height: 1.5;
}

.message-item.query {
  background: #95ec69;
  margin-left: auto;
  margin-right: 10px;
  border-radius: 18px 4px 18px 18px;
  color: #000;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.message-item.response {
  background: #fff;
  margin-right: auto;
  margin-left: 10px;
  color: #000;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.message-item.error {
  background: rgba(245, 108, 108, 0.9);
  margin-right: auto;
  margin-left: 10px;
  color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 消息时间样式 */
.message-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.5);
  text-align: center;
  margin: 10px 0;
}

/* 修改滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 4px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

/* 星空背景 */
.stars {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: 
    radial-gradient(2px 2px at 20px 30px, #eee, rgba(0,0,0,0)),
    radial-gradient(2px 2px at 40px 70px, #fff, rgba(0,0,0,0)),
    radial-gradient(2px 2px at 50px 160px, #ddd, rgba(0,0,0,0)),
    radial-gradient(2px 2px at 90px 40px, #fff, rgba(0,0,0,0)),
    radial-gradient(2px 2px at 130px 80px, #fff, rgba(0,0,0,0));
  background-repeat: repeat;
  background-size: 200px 200px;
  animation: twinkle 5s infinite;
}

/* 流星效果 */
.shooting-stars {
  position: absolute;
  width: 100%;
  height: 100%;
}

.shooting-stars::before,
.shooting-stars::after {
  content: "";
  position: absolute;
  width: 4px;
  height: 4px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 0 0 4px rgba(255,255,255,0.1),
              0 0 0 8px rgba(255,255,255,0.1),
              0 0 20px rgba(255,255,255,1);
}

.shooting-stars::before {
  top: 0;
  left: 0;
  animation: shoot1 6s infinite linear;
}

.shooting-stars::after {
  top: 30%;
  left: 20%;
  animation: shoot2 4s infinite linear;
}

.shooting-stars::before {
  box-shadow: 
    0 0 0 4px rgba(255,255,255,0.1),
    0 0 0 8px rgba(255,255,255,0.1),
    0 0 20px rgba(255,255,255,1),
    100px 200px #fff,
    200px 400px #fff,
    300px 300px #fff;
}

@keyframes twinkle {
  0% { opacity: 0.8; }
  50% { opacity: 0.4; }
  100% { opacity: 0.8; }
}

@keyframes shoot1 {
  0% {
    transform: translate(-100px, 0) rotate(35deg);
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  70% {
    opacity: 1;
  }
  100% {
    transform: translate(calc(100vw + 100px), 100vh) rotate(35deg);
    opacity: 0;
  }
}

@keyframes shoot2 {
  0% {
    transform: translate(-150px, -50px) rotate(30deg);
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  70% {
    opacity: 1;
  }
  100% {
    transform: translate(calc(100vw + 150px), 60vh) rotate(30deg);
    opacity: 0;
  }
}

/* 添加额外的流星类 */
.shooting-stars::after {
  content: "";
  position: absolute;
  width: 3px;
  height: 3px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 0 0 4px rgba(255,255,255,0.1),
              0 0 0 8px rgba(255,255,255,0.1),
              0 0 20px rgba(255,255,255,1);
  animation: shoot3 5s infinite linear;
  top: 50%;
  left: -100px;
}

@keyframes shoot3 {
  0% {
    transform: translate(-100px, -100px) rotate(40deg);
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  70% {
    opacity: 1;
  }
  100% {
    transform: translate(calc(100vw + 200px), 40vh) rotate(40deg);
    opacity: 0;
  }
}

/* 添加可点击数量的样式 */
.clickable-count {
  color: #409EFF;
  margin: 8px 0;
  font-weight: bold;
  cursor: pointer;
}

.clickable-count:hover {
  text-decoration: underline;
}

.process-link {
  color: #F56C6C;
  cursor: pointer;
  font-weight: bold;
  margin-top: 5px;
  display: inline-block;
}

.process-link.disabled {
  color: #999;
  cursor: not-allowed;
  text-decoration: none !important;
}

.process-link:not(.disabled):hover {
  text-decoration: underline;
}

/* 修改表格弹窗样式 */
:deep(.data-dialog .el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  background: rgba(255, 255, 255, 0.95);
}

:deep(.data-dialog .el-dialog__body) {
  padding: 0 !important;
  margin: 0;
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

/* 表格包装容器样式 */
.table-wrapper {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
:deep(.el-table) {
  width: 100% !important;
  border-collapse: collapse;
}

:deep(.el-table__cell) {
  padding: 0 !important;
}

:deep(.el-table .cell) {
  padding: 0 8px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  height: 40px;
}

:deep(.el-table__header-wrapper th.el-table__cell) {
  background: #f5f7fa !important;
  font-weight: bold;
}

:deep(.el-table__body-wrapper td.el-table__cell) {
  background: #ffffff !important;
}

/* 分页容器样式 */
.pagination-container {
  padding: 15px 0;
  background: #fff;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: center;
}

/* 表头和页脚样式 */
:deep(.data-dialog .el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
  text-align: center;
}

:deep(.data-dialog .el-dialog__footer) {
  padding: 20px;
  margin: 0;
  border-top: 1px solid #ebeef5;
  text-align: center;
}

/* 修改表格边框样式 */
:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row:last-child td) {
  border-bottom: 1px solid #ebeef5;
}
</style>
